package top.lingkang.finalsession.solon;

import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.lingkang.finalsession.FinalSessionConfig;
import top.lingkang.finalsession.core.FinalRepository;
import top.lingkang.finalsession.error.FinalBaseException;

/**
 * @author lingkang
 * Created by 2024/5/10
 */
@Component(index = -1995) //index 为顺序位（不加，则默认为0）
public class FinalSessionFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(FinalSessionFilter.class);
    private static boolean load;
    public FinalSessionConfig config = new FinalSessionConfig();
    // 会话存储仓库
    public FinalRepository<FinalSessionState> repository;

    public FinalSessionFilter() {
        if (load)
            throw new FinalBaseException("solon下final-session-solon 已经自动加载");
        load = true;
        config.setSessionHandler(new FinalSessionHandlerCookie());
        config.setIdGenerate(new FinalIdGenerateSolon());
        config.setGenerateSession(new GenerateSessionSolon());
        config.setRepository(new MemoryFinalRepositorySolon());
        repository = config.getRepository();
        repository.initConfig(config);
        // 订阅到 FinalSessionConfig bean注册就修改配置
        Solon.context().subBeansOfType(FinalSessionConfig.class, p -> {
            if (p.getSessionHandler() == null)
                p.setSessionHandler(new FinalSessionHandlerCookie());
            if (p.getIdGenerate() == null)
                p.setIdGenerate(new FinalIdGenerateSolon());
            if (p.getGenerateSession() == null)
                p.setGenerateSession(new GenerateSessionSolon());
            if (p.getRepository() == null)
                p.setRepository(new MemoryFinalRepositorySolon());

            config = p;
            repository = config.getRepository();
            repository.initConfig(config);
            log.info("重新加载了FinalSessionConfig配置.");
        });
        log.info("final-session-solon 插件加载完成，默认使用内存存储session, top.lingkang.finalsession.solon.MemoryFinalRepositorySolon");
    }

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        chain.doFilter(ctx);
        if (FinalSessionState.existsUpdate.get()) {
            FinalSessionState session = (FinalSessionState) ctx.sessionState();
            repository.setSession(session.sessionId(), session);
            // 更新后
            FinalSessionState.existsUpdate.set(false);
        }
    }
}
